package top.zlhy7.lock;

import org.junit.jupiter.api.Test;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author renyong
 * @date 2022/9/12 20:32
 * @description 读写锁练习
 */
// 资源类
class MyCache{
    // 创建集合
    private Map<String,Object> cacheMap = new HashMap<>();
    /**
     * 读写锁对象
     */
    private ReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    /**
     * 存数据
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        reentrantReadWriteLock.writeLock().lock();
        // 暂停一会
        try {
            System.out.println(Thread.currentThread().getName() + "正在写操作" + key);
            TimeUnit.MILLISECONDS.sleep(300);
            cacheMap.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写完了" + key);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
    }
    /**
     * 取数据
     * @param key
     */
    public void get(String key){
        reentrantReadWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读操作"+key);
            // 暂停一会
            TimeUnit.MILLISECONDS.sleep(300);
            Object value = cacheMap.get(key);
            System.out.printf("%s读完了key:%s,value:%s\n",Thread.currentThread().getName(),key,value);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            reentrantReadWriteLock.readLock().unlock();
        }

    }
}
public class ReadWriteLockTest {
    public static void main(String[] args) {
        //ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
        //readWriteLockTest.test1();
        System.out.println(LocalDate.of(2022,5,16).until(LocalDate.of(2022,9,13), ChronoUnit.DAYS));
    }
    /**
     * 锁降级
     * 获取写锁-》获取读锁-》释放写锁-》释放读锁
     */
    @Test
    public  void test2(){

    }
    /**
     * 测试读写锁
     */
    @Test
    public  void test1(){
        MyCache myCache = new MyCache();
        // 创建线程存数据
        for (int i = 1; i < 6+1; i++) {
            int num = i;
            new Thread(()->{
                myCache.put(String.valueOf(num), num);
            },String.valueOf(num)).start();
        }
        // 创建线程取数据
        for (int i = 1; i < 6+1; i++) {
            int num = i;
            new Thread(()->{
                myCache.get(String.valueOf(num));
            },String.valueOf(num)).start();
        }
    }
}
